import { Form, Input, Modal } from 'antd';
import { useImperativeHandle, useState } from 'react';

import rolesApi from '@/api/rolesApi';
import { message } from '@/components/AntdGlobal';
import type { IRole } from '@/types/api';
import type { IAction, IModalProp } from '@/types/modal';

const CreateRole = (props: IModalProp<IRole.RoleItem>) => {
    /* 数据管理 ---------------------------------------------------*/
    const [visible, setVisible] = useState(false);
    const [action, setAction] = useState<IAction>('create');
    const [form] = Form.useForm();

    /* 逻辑代码 ---------------------------------------------------*/
    /**
     * 暴露子组件open方法，供父组件中调用props.mRef?.openModal()方法
     */
    useImperativeHandle(props.mRef, () => {
        return {
            openModal
        };
    });

    /**弹框显示
     * @param action 类型
     * @param data 数据
     */
    const openModal = (action: IAction, data?: IRole.RoleItem) => {
        setVisible(true);
        setAction(action);
        if (action === 'edit' && data) {
            form.setFieldsValue(data);
        }
    };

    /**表单提交
     */
    const handleSubmit = async () => {
        try {
            const valid = await form.validateFields();
            if (valid) {
                const values = form.getFieldsValue();
                if (action === 'create') {
                    await rolesApi.createRole(values);
                    message.success('创建成功');
                } else if (action === 'edit') {
                    await rolesApi.editRole(values);
                    message.success('修改成功');
                }
                // 关闭弹窗，重置表单数据
                handleCancel();
                // 父组件更新列表
                props.update();
            }
        } catch (error) {
            console.error(error);
        }
    };

    /**取消操作
     */
    const handleCancel = () => {
        setVisible(false);
        // 重置表单时机：退出时重置 优于 打开时判断重置
        form.resetFields();
    };
    return (
        <Modal
            title={action === 'create' ? '创建用户' : '编辑用户'}
            width={800}
            open={visible}
            okText="确定"
            cancelText="取消"
            onOk={handleSubmit}
            onCancel={handleCancel}
        >
            <Form
                form={form}
                labelCol={{ span: 4 }}
                labelAlign="right"
            >
                {/* 隐藏提交项,edit时提交 */}
                <Form.Item
                    name="roleId"
                    hidden
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="角色名称"
                    name="roleName"
                    rules={[
                        {
                            required: true,
                            message: '请输入角色名称'
                        }
                    ]}
                >
                    <Input placeholder="请输入角色名称" />
                </Form.Item>
                <Form.Item
                    label="备注"
                    name="remark"
                >
                    <Input.TextArea placeholder="请输入备注" />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default CreateRole;
